<template>
  <div class="singer">
    <list-view :data='SingerList' @toSingerDetail='toSingerDetail'></list-view>
    <transition name='fade'>
      <router-view></router-view>
    </transition>
  </div>
</template>

<script>
import {getSingerList} from 'api/singer'
import {ERR_OK} from 'api/config'
import { mapMutations } from 'vuex'

import singer from 'common/js/singer'
import listView from "base/listview/listview";

const HOT_NAME= '热门歌手'
const HOT_NAME_NUM= 10

  export default {
    data() {
      return {
        SingerList:[]
      }
    },
    components:{
      listView
    },
    methods: {
      toSingerDetail(singer){
        this.$router.push({
          path:`/singer/${singer.id}`
        }),
        this.setSinger(singer)
      },

      ...mapMutations({
        setSinger: 'SET_SINGER' 
        // 将 `this.setSinger()` 映射为 `this.$store.commit('SET_SINGER')`
      }),

      _getSingerList(){
        getSingerList().then(res=>{
            if(res.code===ERR_OK){
              this.SingerList=this.foramtList(res.data.list)
            }
        })
      },
      //格式 歌手列表 我们想要的格式
      foramtList(list){
          let map={
            hotSinger:{
              title:HOT_NAME,
              items:[]
            }
          }
          list.forEach((item,index) => {
            if(index<HOT_NAME_NUM){
              map.hotSinger.items.push(
                new singer({
                  id:item.Fsinger_mid,
                  name:item.Fsinger_name
              })
              )
            }
            const key=item.Findex
            if(!map[key]){
              map[key]={
                title:key,
                items:[]
              }
            }
            map[key].items.push(
              new singer({
                id:item.Fsinger_mid,
                name:item.Fsinger_name
              })
            )
          })

          //根据字母 升序排序
          let hot=[]
          let ref=[]
          for(let key in map ){
             let val=map[key]
             if(val.title.match(/[a-zA-Z]/)){
               ref.push(val)
             }else if(val.title===HOT_NAME){
               hot.push(val)
             }
          }
          ref.sort((a,b)=>{
              return a.title.charCodeAt(0)-b.title.charCodeAt(0)
          })
          return hot.concat(ref)
      }
    },
    created(){
      this._getSingerList()
    }
  }

</script>

<style scoped lang="stylus" >
  .singer
    position: fixed
    top: 88px
    bottom: 0
    width: 100%
  .fade-enter-active, .fade-leave-active 
    transition: all .3s ;
  .fade-enter, .fade-leave-to 
    transform: translateX(10px);
    opacity: 0; 
</style>
